package cn.message.service.impl;

import cn.itcast.mapper.accountMapper;
import cn.itcast.mapper.rechargeMapper;
import cn.itcast.pojo.*;
import cn.message.service.IRechargeService;
import com.github.pagehelper.PageHelper;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 充值记录的业务层
 * @author 郭智超
 * @create 2020-04-06 11:47
 */
@Service
public class RechargeServiceImpl implements IRechargeService {

    @Resource
    private rechargeMapper rechargeMapper;

    @Override
    public Map<String, Object> getAllRecharge(Map<String,String> map) {
        rechargeExample rechargeExample = new rechargeExample();
        rechargeExample.setOrderByClause("recharge_time DESC");
        cn.itcast.pojo.rechargeExample.Criteria criteria = rechargeExample.createCriteria();

        //添加查询条件
        //根据用户名称模糊搜索
        if(!map.get("name").isEmpty()){
            criteria.andNameLike("%"+map.get("name")+"%");
        }
        //根据入账状态模糊查询
        if(!map.get("billState").isEmpty()){
            criteria.andBillStateEqualTo(map.get("billState"));
        }

        String[] dateRanges = {};
        Date startDate = null;
        Date endDate = null;
        if (!map.get("dateRange").isEmpty()) {
            dateRanges = map.get("dateRange").split(",");
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                startDate = sdf.parse(dateRanges[0]);
                endDate = sdf.parse(dateRanges[1]);
                criteria.andRechargeTimeBetween(startDate,endDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        //返回符合查询条件的总记录数
        int count = rechargeMapper.countByExample(rechargeExample);

        int page = Integer.parseInt(map.get("page"));
        int limit = Integer.parseInt(map.get("limit"));
        //分页
        PageHelper.startPage(page, limit);
        //查询所有符合条件的充值记录的信息
        List<recharge> rechargeList = rechargeMapper.selectByExample(rechargeExample);

        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //格式化充值时间、到账时间
        for (cn.itcast.pojo.recharge recharge : rechargeList) {
            if(recharge.getRechargeTime() != null){
                recharge.setRechargeTime_string(sdf.format(recharge.getRechargeTime()));
            }
            if(recharge.getBillTime() != null){
                recharge.setBillTime_string(sdf.format(recharge.getBillTime()));
            }
        }

        Map<String,Object> resultMap = new HashMap<String, Object>();
        resultMap.put("count",count);
        resultMap.put("rechargeList",rechargeList);

        return resultMap;
    }
}
